package com.feng.study.demo.sf;

import java.util.HashMap;

/**
 * LRU-least recently used
 * 最近最少使用算法
 * 淘汰机制
 */
public class LRUDemo {

    private HashMap<Integer,Node> cache =  new HashMap<>();
    private int size;
    private int capacity;
    private Node head,tail;

    public LRUDemo(int capacity){
        this.size=0;
        this.capacity=capacity;

        head=new Node();
        tail=new Node();
        head.next=tail;
        tail.prev=head;
    }

    private int get(int key){
        Node node = cache.get(key);
        if (node==null){
            return -1;
        }
        // 访问了需要挪到队列最前面
        moveToHead(node);
        return node.value;
    }
    private void put(int key, int value){
        Node node = cache.get(key);
        if (node==null){
            Node newNode = new Node();
            newNode.value=value;
            newNode.key=key;
            cache.put(key,newNode);
            addNode(newNode);
            size++;
            if(size>capacity){
                Node tail = popTail();
                cache.remove(tail.key);
                size--;
            }
        }else {
            node.value=value;
            moveToHead(node);
        }
    }

    class Node{
        int key;
        int value;
        Node prev;
        Node next;
    }
    private void addNode(Node node){
        node.prev=head;
        node.next=head.next;

        head.next.prev=node;
        head.next=node;
    }
    private void removeNode(Node node){
        Node next = node.next;
        Node prev = node.prev;

        prev.next=next;
        next.prev=prev;
    }
    private void moveToHead(Node node){
        removeNode(node);
        addNode(node);
    }
    private Node popTail(){
        Node res = tail.prev;
        removeNode(tail);
        return res;
    }
}
